package com.stox.ui.javafx.charting.event.handler;

import java.util.Arrays;

import javafx.event.EventHandler;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import org.springframework.context.ApplicationEventPublisher;

import com.stox.event.AbstractModelSelectionEvent;
import com.stox.model.AbstractModel;
import com.stox.ui.javafx.core.widget.wrapper.TreeItem;
import com.stox.ui.javafx.core.widget.wrapper.TreeView;
import com.stox.ui.javafx.navigator.model.AbstractModelTreeItem;
import com.stox.ui.javafx.navigator.view.AbstractNavigatorTab;
import com.stox.ui.javafx.navigator.view.NavigatorView;
import com.stox.ui.javafx.navigator.view.tab.scrip.ScripNavigatorTab;
import com.stox.util.ApplicationContextUtil;

public class ChartingViewKeyEventHandler implements EventHandler<KeyEvent> {

	public static final ChartingViewKeyEventHandler instance = 
			new ChartingViewKeyEventHandler();
	
	private NavigatorView navigatorView;
	
	private TreeView<String> getTreeView(){
		if(navigatorView == null) 			
			navigatorView = ApplicationContextUtil.getApplicationContext().getBean(NavigatorView.class);
		AbstractNavigatorTab abstractNavigatorTab = navigatorView.getSelectedNavigatorTab();
		if(abstractNavigatorTab == null) 			
			abstractNavigatorTab = ApplicationContextUtil.getApplicationContext().getBean(ScripNavigatorTab.class);
		return abstractNavigatorTab.getTreeView();
	}
	
	private TreeItem<String> getTreeItem(KeyEvent event){
		TreeView<String> treeView = getTreeView();
		TreeItem<String> treeItem = (TreeItem<String>)treeView.getSelectionModel().getSelectedItem();
		treeItem = (TreeItem<String>)(KeyCode.PAGE_DOWN == event.getCode()?treeItem.nextTreeItem() : treeItem.previousTreeItem());
		while(null != treeItem && !(treeItem instanceof AbstractModelTreeItem)) {
			treeItem = (TreeItem<String>)(KeyCode.PAGE_DOWN == event.getCode()?treeItem.nextTreeItem() : treeItem.previousTreeItem());
		}
		int row = treeView.getRow((javafx.scene.control.TreeItem<String>)treeItem);
		treeItem.expand();
		treeView.scrollTo(row);
		treeView.getSelectionModel().clearAndSelect(row);
		return treeItem;
	}
	
	@Override
	public void handle(KeyEvent event) {
		if(KeyCode.PAGE_DOWN == event.getCode() || KeyCode.PAGE_UP == event.getCode()) {
			TreeItem<String> treeItem = getTreeItem(event);
			
			
			if(null != treeItem && treeItem instanceof AbstractModelTreeItem) {
				AbstractModelTreeItem<String> abstractModelTreeItem = (AbstractModelTreeItem<String>)treeItem;
				AbstractModel abstractModel = abstractModelTreeItem.getModel();
				ApplicationEventPublisher applicationEventPublisher = ApplicationContextUtil.getApplicationContext().getBean(ApplicationEventPublisher.class);
				applicationEventPublisher.publishEvent(new AbstractModelSelectionEvent<AbstractModel>(Arrays.asList(abstractModel)));
			}
		}

	}
}
